package cool.tianyou.blue.bird.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import cool.tianyou.blue.bird.Filter;
import cool.tianyou.blue.bird.adapter.LogListAdapter;
import cool.tianyou.blue.bird.constant.Constant;
import cool.tianyou.blue.bird.R;
import cool.tianyou.blue.bird.dialog.RequestUnlockDialog;
import cool.tianyou.blue.bird.model.CommonMessage;
import cool.tianyou.blue.bird.model.NotificationData;
import cool.tianyou.blue.bird.model.vo.DeviceMessage;
import cool.tianyou.blue.bird.receiver.BatteryReceiver;
import cool.tianyou.blue.bird.receiver.PhoneCallReceiver;
import cool.tianyou.blue.bird.service.MQTTMessageCallBack;
import cool.tianyou.blue.bird.service.MQTTService;
import cool.tianyou.blue.bird.service.NotificationService;
import cool.tianyou.blue.bird.service.MQTTServiceConnection;
import cool.tianyou.blue.bird.util.HttpUtil;
import cool.tianyou.blue.bird.util.Listener;
import cool.tianyou.blue.bird.util.LogUtil;
import cool.tianyou.blue.bird.util.SpUtil;
import cool.tianyou.blue.bird.util.Util;

import com.xuexiang.xui.XUI;

import java.util.Collections;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements Listener, MQTTMessageCallBack {

    private static final String TAG = "获取短信";
    private ClipboardManager mClipboardManager;
    private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener;
    BatteryReceiver batteryReceiver = new BatteryReceiver();
    private MQTTServiceConnection mqttServiceConn;
    private BaseAdapter logAdapter;
    private TextView tvLastLog;
    private PhoneCallReceiver phoneCallReceiver;
    private Boolean hasRegisterPhoneCall = false;
    public static MainActivity instance = null;
    private RequestUnlockDialog requestUnlockDialog;
    private Switch pushSwitch;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        XUI.initTheme(this);
        test();
        super.onCreate(savedInstanceState);
        Constant.USER_INFO.TOKEN = SpUtil.getString(this, Constant.SP_CONSTANT.TOKEN, "");

        setContentView(R.layout.activity_main2);
        ListView listView = findViewById(R.id.listView);
        tvLastLog = findViewById(R.id.tv_last_log);
        logAdapter = new LogListAdapter(LogUtil.logs, this);
        pushSwitch = findViewById(R.id.sw_push);
        Boolean pushStatus = (Boolean) SpUtil.get(this, Constant.SP_CONSTANT.MESSAGE_PUSH_STATUS, false);
        pushSwitch.setChecked(pushStatus);
        pushSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            HttpUtil.put(this, ImmutableMap.builder().put("pushState", isChecked).build(), "/device/push/state", apiResult -> {
            });
            SpUtil.put(this, Constant.SP_CONSTANT.MESSAGE_PUSH_STATUS, isChecked);
        });
        listView.setAdapter(logAdapter);
        LogUtil.registerListener(this);
        registerBatteryListener();
        registerClipEvents();
        getBatteryImmediately();
        // 链接 mqtt 服务


        if (mqttServiceConn == null || !mqttServiceConn.isConnected()) {
            mqttServiceConn = new MQTTServiceConnection();
            mqttServiceConn.setIGetMessageCallBack(this);
            Intent mqttIntent = new Intent(this, MQTTService.class);
            bindService(mqttIntent, mqttServiceConn, Context.BIND_AUTO_CREATE);
        }

        requestSMSPermission();
        dealShare();
        registerPhoneCallReceiver(true);
        // 启动通知监听服务
        Intent intent = new Intent(MainActivity.this, NotificationService.class);//启动服务
        startService(intent);//启动服务
        setDefaultConfig();
        Util.getDeviceId(this);
        MainActivity.instance = this;

    }

    private void setDefaultConfig() {

    }

    /**
     * 处理文本分享
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void dealShare() {
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();
        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if ("text/plain".equals(type)) {
                String share = intent.getStringExtra(Intent.EXTRA_TEXT);
                sendAsClipBoard(share);
                Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }


    /**
     * 注册电量广播接收器
     */
    public void registerBatteryListener() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryReceiver, filter);
    }

    public void setting(View v) {
        startActivity(new Intent(MainActivity.this, SettingsActivity.class));
    }

    /**
     * 立即获取电量
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void getBatteryImmediately() {
        Log.e("TAG", "立即获取电量");
        //通过粘性广播读取电量
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent intentBattery = registerReceiver(null, intentFilter);//注意，粘性广播不需要广播接收器
        if (intentBattery != null) {
            batteryReceiver.sendBatteryData(MainActivity.this, intentBattery, true);
        }
    }


    /**
     * 注册剪贴板事件
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void registerClipEvents() {
        mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        mOnPrimaryClipChangedListener = () -> {
            if (mClipboardManager.hasPrimaryClip()
                    && mClipboardManager.getPrimaryClip().getItemCount() > 0) {
                // 获取复制、剪切的文本内容
                CharSequence content =
                        mClipboardManager.getPrimaryClip().getItemAt(0).getText();
                sendAsClipBoard(content.toString());
            }
        };
        mClipboardManager.addPrimaryClipChangedListener(mOnPrimaryClipChangedListener);
    }


    /**
     * 作为剪贴板数据发送
     *
     * @param content
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void sendAsClipBoard(String content) {
        CommonMessage commonMessage = new CommonMessage();
        commonMessage.setNotification(new NotificationData(Icon.createWithResource(this, R.mipmap.clip_board), "剪贴板", content, null));
        commonMessage.putEncryptedData("content", content)
                .setTime(new Date());
        commonMessage.setType("CLIP_BOARD");
        Util.sendMessage(commonMessage.genUuid(), this);
        getBatteryImmediately();
    }


    /**
     * 注销监听，避免内存泄漏。
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("MainActivity", "销毁");
        if (mClipboardManager != null && mOnPrimaryClipChangedListener != null) {
            mClipboardManager.removePrimaryClipChangedListener(mOnPrimaryClipChangedListener);
        }
        if (batteryReceiver != null) {
            unregisterReceiver(batteryReceiver);
        }
        if (phoneCallReceiver != null) {
            registerPhoneCallReceiver(false);
        }
        if (mqttServiceConn != null) {
            unbindService(mqttServiceConn);
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    public void viewMyDevice(View v) {
        getBatteryImmediately();
        Intent intent = new Intent(this, DeviceActivity.class);
        startActivity(intent);

    }

    @Override
    public void call(int type) {
        runOnUiThread(() -> {
            logAdapter.notifyDataSetChanged();
            tvLastLog.setText(LogUtil.lastLog);
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void setMessage(DeviceMessage message) {
        runOnUiThread(() -> {
            System.out.println(message);
            dealMessage(message);
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    void dealMessage(DeviceMessage message) {
        cool.tianyou.blue.bird.model.Log log = new cool.tianyou.blue.bird.model.Log();


        switch (message.getType()) {
            case "REQUEST_UNLOCK":
                ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
                activityManager.moveTaskToFront(this.getTaskId(), 0);
                if (requestUnlockDialog != null) {
                    requestUnlockDialog.dismiss();
                }
                requestUnlockDialog = new RequestUnlockDialog(this, message.getData().get("alias"), Integer.valueOf(message.getData().get("deviceId")))
                        .setAutoDismiss(15000);
                requestUnlockDialog.showDialog();


                break;
            default:
                log.setPkgName("");
                log.setPushedDevices(Collections.singletonList("消息发出设备:" + message.getFromDevice()));
                log.setIcon(Icon.createWithResource(this, R.mipmap.device_message));
                log.setTime(new Date());
                log.setSaveToLogList(true);
                log.setContent(message.getType());
                LogUtil.recordLog(log, this);
        }
        getBatteryImmediately();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        requestSMSPermission();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 10: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.i(TAG, "onRequestPermissionsResult granted");
                } else {
                    Log.i(TAG, "onRequestPermissionsResult denied");
                    if (SpUtil.getString(this, "alert", "").equals("")) {
                        showWaringDialog();
                        SpUtil.putString(this, "alert", "true");
                    }
                }
                return;
            }
            case 0: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    goScanner();
                }
                return;
            }

        }
    }

    private void showWaringDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("将无法在收到短信时同步，其余功能不收影响")
                .setPositiveButton("确定", (dialog1, which) -> {
                }).show();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void sendContent(View v) {
        EditText editText = findViewById(R.id.et_content);
        String s = editText.getText().toString();
        editText.getText().clear();
        if ("".equals(s) || s.trim().length() == 0) {
            return;
        }
        sendAsClipBoard(s);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() != null) {
                Log.d("MainActivity", "Scanned");
                dealQrcode(result.getContents());
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
        getBatteryImmediately();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void dealQrcode(String contents) {


        HttpUtil.get(this, null, "/account/qrcode/scan/" + contents, result -> {
            if (result.getCode() == 200) {
                runOnUiThread(() -> {
                    Intent intent = new Intent(MainActivity.this, LoginConfirmActivity.class);
                    JSONObject data = (JSONObject) result.getData();
                    intent.putExtra("uuid", data.getString("uuid"));
                    startActivity(intent);
                    getBatteryImmediately();
                });
            } else {
                Log.e("登录失败:", "" + ((JSONObject) result.getData()).getString("message"));
            }
        });
    }

    /**
     * 申请权限
     */
    private void requestSMSPermission() {
        Log.i("获取短信权限", "requestPermission");
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, "checkSelfPermission");
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.RECEIVE_SMS)) {
                Log.i(TAG, "shouldShowRequestPermissionRationale");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, 10);

            } else {
                Log.i(TAG, "requestPermissions");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, 10);
            }
        }
    }

    /**
     * 打开扫一扫功能
     */
    private void goScanner() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setOrientationLocked(true);
//        integrator.setCaptureActivity(ScanActivity.class);
        integrator.initiateScan();
    }

    /**
     * 启动扫一扫 获取授权
     *
     * @param v
     */
    public void scan(View v) {
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.CAMERA)) {
                Toast.makeText(MainActivity.this, "二维码扫码需要相机权限", Toast.LENGTH_SHORT).show();

            } else {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.CAMERA},
                        0);
            }
        } else {
            goScanner();
        }

    }

    public void registerPhoneCallReceiver(boolean register) {
        if (register) {
            if (phoneCallReceiver == null) {
                phoneCallReceiver = new PhoneCallReceiver();
                phoneCallReceiver.setOnOnPhoneCallListener(valid -> {
                    new PhoneCallReceiver.OnPhoneCallListener() {

                        @Override
                        public void hasNewCall(boolean valid) {
                            Log.e("电话来了", "电话来了");
                            System.out.println("电话来了");

                        }
                    };
                });
            }
            if (!hasRegisterPhoneCall) {
                hasRegisterPhoneCall = true;
                this.registerReceiver(phoneCallReceiver, new IntentFilter());
            }
        } else {
            if (phoneCallReceiver != null && hasRegisterPhoneCall) {
                hasRegisterPhoneCall = false;
                this.unregisterReceiver(phoneCallReceiver);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void test() {
        Filter our_family = new Filter("com.test.run", "Our Family", "新年快乐！");
        Log.e("通知过滤:", our_family.match("com.test.run", "Our Family", "新年快乐呀") + ""); //false
        Log.e("通知过滤:", our_family.match("com.test.run", "Our Family", "新年快乐！") + ""); //true
        Log.e("通知过滤:", new Filter("com.test.run", "Our Family", null).match("com.test.run", "Our Family", "新年快乐！") + "");
        Log.e("通知过滤:", new Filter("com.test.run", null, null).match("com.test.run", "Our Family", "你好") + "");
    }


}